<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col>
                        <el-form-item label="" prop="launchStatus">
                            <el-select v-model="condition.search.launchStatus"
                                       placeholder="状态">
                                <el-option label="推广中" :value="1"></el-option>
                                <el-option label="已暂停" :value="3"></el-option>
                                <el-option label="已删除" :value="6"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" v-on:click="sync">同步</el-button>
                        </el-form-item>
                        <el-form-item>
                            如果没有数据，请先点击同步～
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-divider content-position="left">推广余额</el-divider>
        <dp-cpc-balance ref="dpCpcBalance" :shop-id="shopId" :shop-name="shopName" size="small"></dp-cpc-balance>
        <div class="plan-tips">
            <div style="color: red">推广通优化步骤</div>
            1：完善基础创意和掌柜说<br/>
            2：如果想获取更多的曝光（热门榜），请尽量把推广竞价靠前<br/>
            3：如果想获取更多的点击（团单销量），请尽量把关键词竞价靠前<br/>
            4：景区和郊区的美团推广效果要高于非景区的，所以在景区的店关键词尽量排在第一名<br/>
            5：常用参考指标：点击率（4%-6%），浏览率（13%-15%），感兴趣率（28%-35%）
        </div>
        <el-divider content-position="left">基础推广</el-divider>
        <el-table
            id="cpcPlanTable"
            :data="tableData"
            size="small"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="50" fixed="left">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="launchName"
                fixed="left"
                label="推广名字">
            </el-table-column>
            <el-table-column
                prop="launchStatus"
                :formatter="formatLaunchStatus"
                label="推广状态">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                fixed="left"
                label="同步时间">
            </el-table-column>
            <el-table-column
                prop="dateTimeStr"
                label="推广时间">
                <template v-slot="scope">
                    <table-popover :text=scope.row.dateTimeStr :length="24"
                                   placeholder="点击查看"></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="cityStr"
                label="推广城市">
            </el-table-column>
            <el-table-column
                prop="dpPrice"
                label="点评报价">
            </el-table-column>
            <el-table-column
                prop="mtPrice"
                label="美团报价">
            </el-table-column>
            <el-table-column
                prop="premiumFlag"
                :formatter="formatBoolean"
                label="关键词">
            </el-table-column>
            <el-table-column label="自动策略" align="center">
                <el-table-column
                    prop="autoPriceFlag"
                    :formatter="formatAutoPriceFlag"
                    label="自动调价">
                </el-table-column>
                <el-table-column
                    prop="autoPriceGap"
                    :formatter="formatAutoPriceGap"
                    label="调价间隔">
                </el-table-column>
                <el-table-column
                    prop="premiumFloatRatio"
                    width="90"
                    label="关键词上浮">
                    <template v-slot="scope">
                        <div v-if="scope.row.premiumFloatRatio">{{ scope.row.premiumFloatRatio }}倍</div>
                        <div v-else></div>
                    </template>
                </el-table-column>
            </el-table-column>
            <el-table-column label="今日数据" align="center">
                <el-table-column
                    prop="todayBudget"
                    label="预算">
                </el-table-column>
                <el-table-column
                    prop="t30001"
                    label="花费">
                </el-table-column>
                <el-table-column
                    prop="t30002"
                    label="曝光">
                </el-table-column>
                <el-table-column
                    prop="u10cpm"
                    width="100"
                    label="千次曝光成本">
                </el-table-column>
                <el-table-column
                    prop="t30003"
                    label="点击">
                </el-table-column>
                <el-table-column
                    prop="t30004"
                    label="点击均价">
                </el-table-column>
                <el-table-column
                    prop="u10001"
                    label="点击率">
                </el-table-column>
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="160px">
                <template v-slot="scope">
                    <div>
                        <el-button type="text" size="small" @click="onDetail(scope.row)">详情</el-button>
                        <el-button type="text" size="small" @click="autoPrice(scope.row)">自动策略</el-button>
                        <el-button type="text" size="small" @click="priceLog(scope.row)">出价日志</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-divider content-position="left">关键词推广</el-divider>
        <dp-cpc-keyword ref="dpCpcKeyword" :shop-id="shopId" :shop-name="shopName" size="small"></dp-cpc-keyword>

        <el-divider content-position="left">数据报告</el-divider>
        <dp-cpc-report ref="dpCpcReport" :shop-id="shopId" :shop-name="shopName" size="small"></dp-cpc-report>

        <el-dialog title="出价日志" width="60%" :visible.sync="priceLogDialogVisible">
            <dp-cpc-log :launch-id="selectedRow.launchId"></dp-cpc-log>
            <div slot="footer" class="dialog-footer">
                <el-button @click="priceLogDialogVisible = false" size="small">关 闭</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="autoPriceTitle" width="100%" :visible.sync="autoPriceDialogVisible">
            <el-form :model="autoPriceForm" label-width="120px" size="mini" :inline="true" label-position="left">
                <el-table
                    size="small"
                    id="strategyTable"
                    :row-style="{height: '80'}"
                    :data="autoPriceForm.strategies"
                    header-cell-class-name="tableHeaderStyle">
                    <el-table-column
                        prop="name"
                        width="120"
                        label="策略名称">
                        <template v-slot="scope">
                            <el-form-item label="">
                                <el-input v-model="scope.row.name" class="item"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="platform"
                        width="100"
                        align="center"
                        label="平台">
                        <template v-slot="scope">
                            <el-form-item label="">
                                <el-select v-model="scope.row.platform">
                                    <el-option label="点评" :value="1"></el-option>
                                    <el-option label="美团" :value="2"></el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="timesList"
                        width="180"
                        align="center"
                        label="时间段">
                        <template v-slot="scope">
                            <el-form-item label="">
                                <el-select v-model="scope.row.timesList" multiple collapse-tags
                                           @change="(val) => timesSelected(val, scope.$index)">
                                    <el-option-group
                                        v-for="group in getOptions(scope.$index)"
                                        :key="group.label"
                                        :label="group.label">
                                        <el-option
                                            v-for="item in group.options"
                                            :key="item.value"
                                            :label="item.label"
                                            :disabled="getDisable(item.value, scope.$index)"
                                            :value="item.value">
                                        </el-option>
                                    </el-option-group>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="normal"
                        align="center"
                        label="正常出价策略">
                        <el-table-column
                            prop="strategy"
                            width="100"
                            label="出价策略">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-select v-model="scope.row.strategy" clearable>
                                        <el-option label="固定" value="FIXED"></el-option>
                                        <el-option label="排名" value="RANK"></el-option>
                                        <el-option label="智能" value="SMART"></el-option>
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="price"
                            label="固定出价">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-input v-model="scope.row.price"
                                              v-if="scope.row.strategy === 'FIXED'"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="rank"
                            label="选择排名">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-select v-model="scope.row.rank"
                                               v-if="scope.row.strategy === 'RANK'">
                                        <el-option label="第一名" :value="1"></el-option>
                                        <el-option label="第二名" :value="2"></el-option>
                                        <el-option label="第三名" :value="3"></el-option>
                                        <el-option label="第四名" :value="4"></el-option>
                                        <el-option label="第五名" :value="5"></el-option>
                                        <el-option label="第六名" :value="6"></el-option>
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="overPrice"
                            label="排名溢价">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-input v-model="scope.row.overPrice"
                                              v-if="scope.row.strategy === 'RANK'"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="maxPrice"
                            label="最高出价">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-input v-model="scope.row.maxPrice"
                                              v-if="scope.row.strategy === 'RANK' || scope.row.strategy === 'SMART'"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="minPrice"
                            label="最低出价">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-input v-model="scope.row.minPrice"
                                              v-if="scope.row.strategy === 'SMART'"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table-column>
                    <el-table-column
                        prop="keyword"
                        align="center"
                        label="关键词出价策略">
                        <el-table-column
                            prop="keywordStrategy"
                            width="100"
                            label="出价策略">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-select v-model="scope.row.keywordStrategy" clearable>
                                        <el-option label="固定" value="FIXED"></el-option>
                                        <el-option label="排名" value="RANK"></el-option>
                                        <el-option label="智能" value="SMART"></el-option>
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="keywordPrice"
                            label="固定出价">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-input v-model="scope.row.keywordPrice"
                                              v-if="scope.row.keywordStrategy === 'FIXED'"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="keywordRank"
                            label="选择排名">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-select v-model="scope.row.keywordRank"
                                               v-if="scope.row.keywordStrategy === 'RANK'">
                                        <el-option label="第一名" :value="1"></el-option>
                                        <el-option label="第二名" :value="2"></el-option>
                                        <el-option label="第三名" :value="3"></el-option>
                                        <el-option label="第四名" :value="4"></el-option>
                                        <el-option label="第五名" :value="5"></el-option>
                                        <el-option label="第六名" :value="6"></el-option>
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="keywordOverPrice"
                            label="排名溢价">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-input v-model="scope.row.keywordOverPrice"
                                              v-if="scope.row.keywordStrategy === 'RANK'"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="keywordMaxPrice"
                            label="最高出价">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-input v-model="scope.row.keywordMaxPrice"
                                              v-if="scope.row.keywordStrategy === 'RANK' || scope.row.keywordStrategy === 'SMART'"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="keywordMinPrice"
                            label="最低出价">
                            <template v-slot="scope">
                                <el-form-item label="">
                                    <el-input v-model="scope.row.keywordMinPrice"
                                              v-if="scope.row.keywordStrategy === 'SMART'"></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        fixed="right"
                        align="center"
                        width="60">
                        <template v-slot="scope">
                            <div>
                                <el-button type="text" size="small" @click="deletePriceStrategy(scope.$index)">删除
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <el-divider></el-divider>
                <el-row>
                    <el-form-item label="自动调价">
                        <el-switch v-model="autoPriceForm.autoPriceFlag"></el-switch>
                    </el-form-item>
                    <el-form-item label="调价间隔">
                        <el-select v-model="autoPriceForm.autoPriceGap" style="width:120px;">
                            <el-option label="每小时" value="HOURS"></el-option>
                            <el-option label="每10分钟" value="TEN_MINUTES"></el-option>
                            <el-option label="每20分钟" value="TWENTY_MINUTES"></el-option>
                            <el-option label="每半小时" value="HALF_HOUR"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="关键词上浮比例">
                        <el-select v-model="autoPriceForm.premiumFloatRatio" style="width:100px;">
                            <el-option label="不变" :value="1"></el-option>
                            <el-option label="10%" :value="1.1"></el-option>
                            <el-option label="15%" :value="1.15"></el-option>
                            <el-option label="20%" :value="1.2"></el-option>
                            <el-option label="25%" :value="1.25"></el-option>
                            <el-option label="30%" :value="1.3"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="立即调价">
                        <el-switch v-model="autoPriceForm.setPriceNow"></el-switch>
                    </el-form-item>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addPriceStrategy" type="success" size="small">添加策略</el-button>
                <el-button @click="exportStrategyExcel" type="danger" size="small">下 载</el-button>
                <el-button @click="autoPriceDialogVisible = false" size="small">取 消</el-button>
                <el-button @click="autoPriceConfirm" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getDpCpcPlanByPage,
    getDpCpcPlanFields,
    getDpCpcPlanStrategy,
    setDpCpcPlanStrategy,
    syncDpCpcPlan,
} from '@/api/api'
import TablePopover from "@/component/single/TablePopover";
import DpCpcLog from "@/component/DpCpcLog";
import DpCpcReport from "@/component/DpCpcReport";
import DpCpcKeyword from "@/component/DpCpcKeyword";
import DpCpcBalance from "@/component/DpCpcBalance";

export default {
    name: "DpCpcPlan",
    components: {DpCpcLog, DpCpcReport, TablePopover, DpCpcKeyword, DpCpcBalance},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {
                    launchStatus: 1
                }
            },
            // 表格数据
            tableData: [],
            // 选中行
            selectedRow: {},

            // 字段信息
            fields: this.CONST.cpc_fields,
            // 原来保存原来点击的日期
            beforeDate: '',

            // 时间选项
            dp_times_options: this.CONST.cpc_time_options,
            dp_times_selected: [],
            mt_times_options: this.CONST.cpc_time_options,
            mt_times_selected: [],

            // 自动出价策略
            autoPriceDialogVisible: false,
            autoPriceTitle: '',
            autoPriceForm: {
                autoPriceFlag: false,
                autoPriceGap: '',
                setPriceNow: false,
                premiumFloatRatio: '1.1',
                onlyPremiumFlag: false,
                strategies: [],
            },

            // 出价日志
            priceLogDialogVisible: false,
            priceLogForm: {},
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        shopId: String,
        shopName: String,
        size: {
            type: String,
            default: 'small'
        },
    },
    watch: {
        shopName: function (val, oldVal) {
            this.shopName = val;
        }
    },
    computed: {},
    methods: {
        getDisable(val, index) {
            let platform = this.autoPriceForm.strategies[index].platform;
            let timesList = this.autoPriceForm.strategies[index].timesList;
            if (timesList && timesList.indexOf(val) >= 0) {
                return false;
            }
            if (platform === 1) {
                if (this.dp_times_selected.indexOf(val) >= 0) {
                    return true;
                } else {
                    return false;
                }
            } else {
                if (this.mt_times_selected.indexOf(val) >= 0) {
                    return true;
                } else {
                    return false;
                }
            }
        },
        timesSelected(val, index) {
            this.dp_times_selected = [];
            this.mt_times_selected = [];
            let platform = this.autoPriceForm.strategies[index].platform;
            this.autoPriceForm.strategies.forEach((item, index, arr) => {
                if (item.platform === platform) {
                    if (platform === 1) {
                        this.dp_times_selected.push(...item.timesList)
                    } else {
                        this.mt_times_selected.push(...item.timesList)
                    }
                }
            })
        },
        getOptions(index) {
            if (this.autoPriceForm.strategies[index].platform === 1) {
                return this.dp_times_options;
            } else {
                return this.mt_times_options;
            }
        },
        getProp(prop) {
            return "data." + prop;
        },
        sync() {
            let params = {};
            params.shopId = this.shopId;
            syncDpCpcPlan(params).then(data => {
                if (data.respCode == 1000) {
                    this.getData();
                }
            });
        },
        deletePriceStrategy(index) {
            this.autoPriceForm.strategies.splice(index, 1);
            this.dp_times_selected = [];
            this.mt_times_selected = [];
            this.autoPriceForm.strategies.forEach((item, index, arr) => {
                if (item.platform === 1) {
                    this.dp_times_selected.push(...item.timesList)
                } else {
                    this.mt_times_selected.push(...item.timesList)
                }
            })
        },
        addPriceStrategy() {
            let strategy = {};
            // 默认点评
            strategy.platform = 1;
            this.autoPriceForm.strategies.push(strategy);
        },
        autoPrice(row) {
            this.dp_times_selected = [];
            this.mt_times_selected = [];
            this.autoPriceTitle = row.launchName + "出价策略";
            this.autoPriceDialogVisible = true;
            this.autoPriceForm.launchId = row.launchId;
            if (row.autoPriceFlag) {
                this.autoPriceForm.autoPriceFlag = row.autoPriceFlag;
            } else {
                this.autoPriceForm.autoPriceFlag = false;
            }
            this.autoPriceForm.autoPriceGap = row.autoPriceGap;
            this.autoPriceForm.premiumFloatRatio = row.premiumFloatRatio;
            this.autoPriceForm.onlyPremiumFlag = row.onlyPremiumFlag;
            this.autoPriceForm.setPriceNow = false;
            getDpCpcPlanStrategy({'launchId': row.launchId}).then(data => {
                if (data.respCode == 1000) {
                    if (data.body) {
                        this.autoPriceForm.strategies = data.body;
                        this.autoPriceForm.strategies.forEach((item, index, arr) => {
                            if (item.platform === 1) {
                                this.dp_times_selected.push(...item.timesList)
                            } else {
                                this.mt_times_selected.push(...item.timesList)
                            }
                        })
                    } else {
                        this.autoPriceForm.strategies = [];
                    }
                }
            })
        },
        autoPriceConfirm() {
            this.autoPriceForm.strategies.forEach((item, index, arr) => {
                if (item.keywordStrategy === '') {
                    item.keywordStrategy = null;
                }
                if (item.strategy === '') {
                    item.keywordStrategy = null;
                }
            })
            setDpCpcPlanStrategy(this.autoPriceForm).then(data => {
                if (data.respCode == 1000) {
                    this.autoPriceDialogVisible = false;
                    this.getData();
                }
            })
        },
        priceLog(row) {
            this.selectedRow = row;
            this.priceLogDialogVisible = true;
        },
        onDetail: function (row) {
            this.$router.push({
                path: '/dp/cpc/plan/detail',
                query: {id: row.id, launchId: row.launchId, shopId: row.shopId}
            });
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        // 格式状态
        formatLaunchStatus: function (row, column, cellValue) {
            if (cellValue == 1) {
                return "推广中";
            } else if (cellValue == 3) {
                return "已暂停";
            } else if (cellValue == 6) {
                return "已删除";
            } else {
                return "未知";
            }
        },
        // 格式化自动调价
        formatAutoPriceFlag: function (row, column, cellValue) {
            if (cellValue) {
                return "开启";
            } else {
                return "关闭";
            }
        },
        // 格式化调价间隔
        formatAutoPriceGap: function (row, column, cellValue) {
            if (cellValue === undefined) {
                return "";
            }
            if (cellValue === 'TEN_MINUTES') {
                return "每十分钟";
            } else if (cellValue === 'TWENTY_MINUTES') {
                return "每二十分钟";
            } else if (cellValue === 'HOURS') {
                return "每小时";
            } else if (cellValue === 'HALF_HOUR') {
                return "每半小时";
            } else {
                return "未知";
            }
        },
        // 格式平台
        formatPlatform: function (row, column, cellValue) {
            if (cellValue) {
                return "点评";
            } else {
                return "美团";
            }
        },
        formatTimestamp: function (row, column, cellValue) {
            return this.GLOBAL.timestampFormat(cellValue / 1000);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#cpcPlanTable', this.shopName + '推广通数据.xlsx');
        },
        exportStrategyExcel: function () {
            this.GLOBAL.exportExcel('#strategyTable', this.autoPriceTitle + '.xlsx');
        },
        // 获取表格数据
        getData: function () {
            if (this.shopId) {
                this.condition.search.shopId = this.shopId;
            }
            getDpCpcPlanByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
            });
        },
        // 获取字段
        getFields() {
            getDpCpcPlanFields({}).then(data => {
                this.fields = data.body;
            })
        },
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-form--inline .el-form-item {
    margin-right: 0;
}

/deep/ .el-input__inner {
    padding: 0 5px;
}

.plan-tips {
    text-align: left;
    vertical-align: middle;
    font-size: 10px;
    color: #E6A23C;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    line-height: 20px;
}
</style>
